package zjitc.dao.impl;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import zjitc.dao.TestDao;
import zjitc.domain.Test;
import zjitc.util.JDBCUtil;

import java.util.List;

public class TestDaoImpl implements TestDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtil.getDataSource());
    @Override
    public List<Test> findAll() {
        //使用JDBC操作数据库...
        //1. 定义sql
        String sql = "select * from test";
        List<Test> users = template.query(sql, new BeanPropertyRowMapper<Test>(Test.class));
        System.out.println(users);
        return users;
    }

    @Override
    public void addUser(Test user) {
        //1.定义sql
        String sql = "insert into test values(?,?,?,null,null)";
        //2. 执行sql
        template.update(sql,user.getName(),user.getAge(),user.getSex());
    }

    @Override
    public void deleteUser(String name) {
        //1. 定义sql
        String sql = "delete from test where name=?";
        //2. 执行sql
        template.update(sql,name);
    }

    @Override
    public void updateUser(Test user,String checkName) {
        //1. 定义sql
        String sql = "update test set name=?,age=?,sex=? where name=?";
        //2. 执行sql
        template.update(sql,user.getName(),user.getAge(),user.getSex(),checkName);
    }

    @Override
    public Test findByName(String name) {
        //1. 定义sql
        String sql = "select * from test where name = ?";
        return template.queryForObject(sql,new BeanPropertyRowMapper<Test>(Test.class),name);
    }

    @Override
    public void registerUser(Test user) {
        //1. 定义sql
        String sql = "insert into test values(?,?,?,?,?)";
        //2. 执行sql
        template.update(sql,user.getName(),user.getAge(),user.getSex(),user.getPassword(),user.getUsername());
    }
}
